package com.lhb.handler;

import com.lhb.constant.MessageConstant;
import com.lhb.exception.BaseException;
import com.lhb.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param e
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException e)
    {
         log.info("异常信息:{}", e.getMessage());


         return Result.error(e.getMessage());

    }

    /**
     * 捕获sql唯一性约束违反
     * @param e
     * @return
     */
    @ExceptionHandler
    public  Result exptionHandler(SQLIntegrityConstraintViolationException e)
    {
            String message=e.getMessage();

            if(message.contains("Duplicate entry"))
            {
                String[] split = message.split(" ");

                String username=split[2];

               String errorMessage=username+ MessageConstant.ALREADY_EXISTS;

               return Result.error(errorMessage);


            }
            else{
                return Result.error(MessageConstant.UNKNOW_ERROR);
            }




    }







}
